package com.mg.demo;

import android.app.Activity;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.ushaqi.zhuishushenqi.OfflineBook;
import com.ushaqi.zhuishushenqi.ZSPlugin;

import java.util.ArrayList;
import java.util.List;

public class BookListAdapter extends RecyclerView.Adapter<BookListAdapter.ViewHolder> {

    private List<OfflineBook> books = new ArrayList<>();

    private Activity activity;
    String ticket;

    public BookListAdapter(Activity activity,String ticket) {
        this.activity = activity;
        this.ticket=ticket;
    }

    public void addBooks(List<OfflineBook> books) {
        this.books.addAll(books);
        notifyDataSetChanged();
    }

    @Override
    public BookListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new BookListAdapter.ViewHolder(LayoutInflater.from(activity).inflate(R.layout.item_book_list, parent, false));
    }

    @Override
    public void onBindViewHolder(BookListAdapter.ViewHolder holder, int position) {
        final OfflineBook offlineBook = books.get(position);
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(offlineBook.getCover()))
                .setProgressiveRenderingEnabled(true)
                .build();
        PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                .setImageRequest(request)
                .build();

        holder.mIcCover.setController(controller);

        holder.mTvName.setText(offlineBook.title);



       holder.itemView.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               ZSPlugin.get().openReaderCarryTicket(activity,ticket,offlineBook._id,"zhuixiaoshuo");
           }
       });


    }

    @Override
    public int getItemCount() {
        return books.size();
    }

     static class ViewHolder extends RecyclerView.ViewHolder {

         SimpleDraweeView mIcCover;
        TextView mTvName;

        public ViewHolder(View itemView) {
            super(itemView);
            mIcCover = (SimpleDraweeView) itemView.findViewById(R.id.ic_cover);
            mTvName = (TextView) itemView.findViewById(R.id.tv_name);
        }
    }

}
